package xin.nick.controller;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.nick.config.SystemProperties;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author Nick
 * @since 2023/3/22
 */
@Slf4j
@Controller
//@RequestMapping("/api")
//@RequiredArgsConstructor
public class LoginController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SystemProperties systemProperties;

    @GetMapping("/authorize")
    public void authorize(HttpServletResponse response) {

        try {
            // 构造授权链接
            String redirectUrl = systemProperties.getMpRedirectUrl();
//            redirectUrl = URLEncoder.encode(systemProperties.getMpRedirectUrl(), "UTF-8");
            String url = wxMpService.getOAuth2Service().buildAuthorizationUrl(redirectUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, "STATE");
            log.info("授权URL: " + url);
            response.sendRedirect(url);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 微信公众号登录
     * @param code
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(String code) {
        log.info("微信公众号登录,code为: " + code);
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            log.info("登录的用户为: {}", JSON.toJSONString(userInfo));
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        return "欢迎: ********************************";

    }

}
